package cn.itsource.shiro.realm;

import cn.itsource.crm.domain.Employee;
import cn.itsource.crm.service.IEmployeeService;
import cn.itsource.crm.service.IPermissionService;
import cn.itsource.shiro.utils.MyMD5Util;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @author xjh
 * @date 2020/3/29 23:14
 */
public class AuthenRealm extends AuthorizingRealm {

    @Autowired
    IEmployeeService employeeService;

    @Autowired
    IPermissionService permissionService;

    /*授权方法*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到主体用户
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();

        //从数据库获取用户所拥有的权限
        Set<String> permissions = permissionService.findPermissionssnsByLoginUser(employee.getId());
        /*判断是否租户,租户授予管理角色的权限*/
        Boolean isTenant = employee.getIsTenant();
        if(isTenant){
            permissions.add("role:*");
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        /*把用户所拥有的权限给到shiro,判断用户可以访问哪些url*/
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    /*认证方法*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //拿到token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //获取前台登录用户
        String username = token.getUsername();
        //根据用户名查询数据
        Employee employee = employeeService.getByUsername(username);
        if(employee==null){
            throw new UnknownAccountException(username);
        }
        //把用户赋值 principal
        Object principal = employee;
        //取到数据库密码
        Object hashedCredentials = employee.getPassword();
        //盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(MyMD5Util.SALT);
        String realmName = getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,hashedCredentials,
                credentialsSalt,realmName);
        return info;
    }
}